package com.atguigu.gmall.common.util;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;


import com.alibaba.fastjson2.JSONWriter;
import com.fasterxml.jackson.core.type.TypeReference;
import lombok.extern.slf4j.Slf4j;

import java.lang.reflect.Type;

/**
 * @author A
 * @version 1.0
 * @description: TODO
 * @date 2024/9/13 1:50
 */
@Slf4j
public class JsonUtil {

    public static String obj2Json(Object o){
        String jsonString = null;
        try {
            jsonString = JSON.toJSONString(o, JSONWriter.Feature.WriteNulls);
        } catch (Exception e) {
            log.error("对象转json字符串异常: {}",o);
        }
        return jsonString;
    }

    public static <T> T json2Obj(String str, TypeReference<T> typeReference){
        Type type = typeReference.getType();
        T t = null;
        try {
            t = JSONObject.parseObject(str,type);
        } catch (Exception e) {
            log.error("json字符串转对象异常: {}",str);
        }
        return t;
    }
}
